package com.adresvseti.wallpaperoid.services;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;

import com.adresvseti.wallpaperoid.constants.Settings;

import android.os.AsyncTask;
import android.util.Log;

/**
 * Downloads xml from url in separate thread.
 *
 */
public class DownloadXmlTask extends AsyncTask<String, Void, String> {

	private IDownloadXmlSuccessCallback successCallback;
	
	
	public DownloadXmlTask(IDownloadXmlSuccessCallback successCallback)
	{
		this.successCallback = successCallback;
	}
	
	@Override
	protected String doInBackground(String... urls) {
		
		try {
            return downloadUrl(urls[0]);
        } catch (IOException e) {
            return null;
        }
	}
	
    @Override
    protected void onPostExecute(String result) {
    	successCallback.success(result);
    }
		
	private String downloadUrl(String downloadUrl) throws IOException {
	     
		InputStream is = null;

		try {
			URL url = new URL(downloadUrl);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
			conn.setReadTimeout(10000);
			conn.setConnectTimeout(15000);
			conn.setRequestMethod("GET");
			conn.setDoInput(true);

			// connecting
			conn.connect();

			int response = conn.getResponseCode();
			Log.d(Settings.DEBUG_TAG, url + ": " + response);
			
			is = conn.getInputStream();

			// Convert the InputStream into a string
			String contentAsString = readIt(is);
			return contentAsString;

			// Makes sure that the InputStream is closed after the app is
			// finished using it.
		} finally {
			if (is != null) {
				is.close();
			} 
		}
	 }
	 
	// Reads an InputStream and converts it to a String.
	 public String readIt(InputStream stream) throws IOException, UnsupportedEncodingException {
		 
		 java.util.Scanner s = new java.util.Scanner(stream).useDelimiter("\\A");
		 return s.hasNext() ? s.next() : "";
	 }

}
